//
//  AuctionListVC.swift
//  LeGou
//
//  Created by lxm on 2022/10/15.
//

import UIKit
import JXPagingView

class AuctionAutoListVC: ZMViewController, UITableViewDelegate, UITableViewDataSource, ListRequestObjct {

    //MARK: --------------------属性--------------------
    var scrollViewDidScrollBlock: ((UIScrollView) -> ())?
    
    var listData = [ListModel]()
    var page = 1
    var pageSize = 10
    var refreshScrollView : UIScrollView {
        tableView
    }
    
    let timer = Observable<Int>.timer(.seconds(0), period: .seconds(1), scheduler: MainScheduler.instance)
    
    let changeString = ZMUtil.fastBehavior(value: ChangeTitle())
    
    var allSelect = ZMUtil.fastNilBehavior(type: Bool.self)
    //MARK: --------------------UI控件--------------------
    let tableView = UITableView().then { t in
        t.separatorStyle = .none
    }
    
    //MARK: --------------------生命周期--------------------
    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
        bindAction()
        addConstraints()
        getList()
    }

    //MARK: --------------------UI--------------------
    func setUI() {
        tableView.delegate = self
        tableView.dataSource = self
        tableView.estimatedRowHeight = 164
        tableView.rowHeight = UITableView.automaticDimension
        view.addSubview(tableView)
        tableView.zm.register(nibName: "AuctionAutoCell", reuserId: "AuctionAutoCell")
        tableView.backgroundColor = "#F5F5F5".zm.hex()
        tableView.showsVerticalScrollIndicator = false
        tableView.showsHorizontalScrollIndicator = false
        
        addNodataScrollView(scrollView: tableView)
        emptyTitle = "暂无数据"
        emptyImg = "nodata"
        
        tableView.reloadData()
    }
    
    func addConstraints() {
        tableView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
    
    //MARK: --------------------methods--------------------
    func bindAction() {
        timer.subscribe(onNext:{ [unowned self] resp in
            self.changeString.accept(self.getTipsString())
        }).disposed(by: disposeBag)
        
        
    }
    
    // 更新当前文字显示
    func getTipsString() -> ChangeTitle {
        let change = ChangeTitle()
//        guard let ac = activity else {return change}
//        let start = AuctionService.shared.dateFromToday(.milliseconds(ac.startTime))
//        let end = AuctionService.shared.dateFromToday(.milliseconds(ac.endTime))
//        if ac.state == .wait {
//            change.wait = "\(start.zm.toString("HH:mm"))-\(end.zm.toString("HH:mm"))"
//        } else if ac.state == .process {
//            let endTimeInterval = end.timeIntervalSince1970
//            let count = AppHelper.countTime(now: RedBagService.shared.nowTimeinterval, end: endTimeInterval)
//            change.h = String(format: "%02d", count.h)
//            change.m = String(format: "%02d", count.m)
//            change.s = String(format: "%02d", count.s)
//        }
        return change
    }
    
    func refresh() {
        page = 1
        getList()
    }
    
    func getList(_ complete : (()->())? = nil) {
        AuctionAPI.getAutoGoods.rxRequest(type: [ListModel].self).subscribe(onNext:{ [unowned self] resp in
            ZMToast.hiddenActivity()
            self.listData = resp
            self.tableView.reloadData()
            self.checkAllSelect()
            if let complete = complete {
                complete()
            }
        }, onError: { e in
            if let complete = complete {
                complete()
            }
        }).disposed(by: disposeBag)
        
        
//        ZMAPIManage<[ListModel]>.rxSendRequest(AuctionAPI.getAutoGoods).subscribe(onNext:{ [unowned self] resp in
//            ZMToast.hiddenActivity()
//            listRequest(resp)
//            self.checkAllSelect()
//            if let complete = complete {
//                complete()
//            }
//        }, onError: { e in
//            if let complete = complete {
//                complete()
//            }
//        }).disposed(by: disposeBag)
    }
    
    func checkAllSelect() {
        let canArray = self.listData.filter({$0.state == nil || $0.state == .stop})
        if canArray.count == 0 {
            self.allSelect.accept(nil)
        } else {
            let selectAll = !canArray.contains(where: {$0.select == false})
            self.allSelect.accept(selectAll)
        }
    }
    
    func selectAll() {
        guard let allSelect = self.allSelect.value else {
            return
        }
        if allSelect {
            self.listData.filter({$0.state == nil || $0.state == .stop}).forEach({$0.select = false})
        } else {
            self.listData.filter({$0.state == nil || $0.state == .stop}).forEach({$0.select = true})
        }
        self.checkAllSelect()
        self.tableView.reloadData()
    }
    
    /// 报名
//    func onSign(ids : String) {
//        if ids.count == 0 {
//            return
//        }
//        ZMToast.showActivity()
//        AuctionAPI.enroll(["ahProductIds" : ids]).rxRequestNullAble(type: Any.self).subscribe(onNext:{ [unowned self] resp in
//            self.getList();
//        }).disposed(by: disposeBag)
//    }
    
    func oneKeySign() {
        let datas = self.listData.filter({($0.state == nil || $0.state == .stop) && $0.select})
        if datas.count == 0 {
            ZMToast.showToast(title: "请选择")
            return
        }
        ZMAlertView.show(content: "确定要报名吗？", left: "取消", right: "确定", onLeft: nil) {
            self.onSign(datas: datas)
        }
    }
    
    func onSign(datas : [ListModel]) {
        if datas.count == 0 {
            ZMToast.showToast(title: "请选择")
            return
        }
        let r = datas.filter({$0.state == .stop}).map({"\($0.ahProductId)"}).joined(separator: ",")
        let n = datas.filter({$0.state == nil}).map({"\($0.ahProductId)"}).joined(separator: ",")
        
        var requests = [Observable<Any?>]()
        
        if n.count > 0 {
            requests.append(AuctionAPI.enroll(["ahProductIds" : n]).rxRequestNullAble(type: Any.self))
        }
        if r.count > 0 {
            requests.append(AuctionAPI.recoverAutoAuction(["ahProductIds" : r]).rxRequestNullAble(type: Any.self))
        }
        ZMToast.showActivity()
        Observable.combineLatest(requests).subscribe(onNext:{ [unowned self] resp in
            self.getList();
        }).disposed(by: disposeBag)
    }
    
    //MARK: --------------------delegate--------------------
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        tableView.mj_footer?.isHidden = listData.count == 0
        return listData.count
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let data = listData[indexPath.row]
        let vc = AuctionAutoDetailVC()
        vc.id = data.ahProductId
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "AuctionAutoCell") as! AuctionAutoCell
        let data = listData[indexPath.row]
        cell.img.zm.setImage(urlStr: data.image)
        cell.name.text = data.name
        cell.subTitle.text = "您已累计参与\(data.joinCount)次  获得 \(data.giveCount) 件"
        cell.bail.text = data.bail.zm.roundingDown(keep: 2)
        cell.startPrice.text = data.startPrice.zm.roundingDown(keep: 2)
        cell.sign.text = "\(data.enrollCount)人"
        cell.onButton = { [weak self] in
            guard let self = self else {return}
            if data.state == nil || data.state == .stop {
                // 报名
                ZMAlertView.show(content: "确定要报名吗？", left: "取消", right: "确定", onLeft: nil) {
                    self.onSign(datas: [data])
                }
            }
        }
        
        cell.selectBtn.rx.tap.subscribe(onNext:{ [unowned self] resp in
            data.select = !data.select
            self.tableView.reloadData()
            self.checkAllSelect()
        }).disposed(by: cell.disposeBag)
        
        if data.state == nil || data.state == .stop {
            cell.selectBtn.isEnabled = true
            cell.selectBtn.isSelected = data.select
        } else {
            cell.selectBtn.isEnabled = false
            cell.selectBtn.isSelected = false
        }
        
        cell.setStyle(s: cell.map(s: data.state, interruptType: data.interruptType))
        return cell
    }
    
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {

    }
    
    func scrollViewDidScroll(_ scrollViewDidScorllBolck: @escaping ((UIScrollView) -> ())) {
        scrollViewDidScrollBlock = scrollViewDidScorllBolck
    }
    
//    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
//        164
//    }
//
//    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
//        164
//    }
}

extension AuctionAutoListVC : JXPagingViewListViewDelegate {
    func listScrollView() -> UIScrollView { tableView }
    
    func listView() -> UIView {
        return view
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if let scrollViewDidScrollBlock = scrollViewDidScrollBlock {
            scrollViewDidScrollBlock(scrollView)
        }
        listViewDidScrollCallback?(scrollView)
    }
}

extension AuctionAutoListVC {
    class ChangeTitle {
        var wait : String? = nil
        var h = ""
        var m = ""
        var s = ""
    }
    
    class ListModel : HandyJSON {
        required init(){}
        var select = false
        var activityId: Int = 0
        var ahProductId: Int = 0
        var bail : Double = 0.0
        var enrollCount: Int = 0
        var giveCount: Int = 0
        var image = ""
        var interruptType: Int = 0
        var joinCount: Int = 0
        var name = ""
//        var productId: Int = 0
        var productSnapShot = ""
        var startPrice = 0.0
        var state : AuctionModels.AutoState? = nil
        var unrealConflate: Int = 0
        var unrealEnroll: Int = 0
    }
}
